#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

#define	POOL_MAX 10	


//任务队列链表	  //临界资源
typedef struct Task
{
	void* (*work)(void* agr);		//要处理任务的指针
	void* agr;						//参数
	struct Taks *next;				//指向下一个任物、


}Task;


//线程池结构体
typedef struct Thread_Pool
{
	pthread_mutex_t tasklock;	//访问任务链表，是临界资源 互斥锁
	pthread_cond_t newtask;		//通知

	ptread_t tid[POOL_MAX];		//创建线程数量
	Task* head;					//队列头部		
	int busywork				//工作状态

}Thread_Pool


//1. 创建线程池
Thread_Pool* pool;


//2.初始化线程
void pool_init()
{
	//申请空间创建线程池
	pool = (Thread_Pool ) malloc(sizeof(Pool));
	if(pool == NULL)
	{
		perror("malloc");
	}

	//动态初始化条件和互斥量
	pthread_t mutex_init(&tasklock);
	pthread_t cond_init(newtask);
	
	//初始化线程池
	Pool->head = NULL;
	Pool->busywoskl = 0;

	//创建线程数量
	for(i = 0; i < POOL_MAX, i++)
	{
		pthread_create(&tid[i], NULL, work, (void *)i+1);
	}
	
}



//需要处理的任务
void* realword(void *arg)
{
	printf("Finish work %d\n",(int)arg);
}



//3.线程池添加
void pool_add_task()
{
	pthread_mutex_lock(&tasklock);			   //加锁

	//判断是否有空闲的现存
	while(pool->busywosk >= POOL_MAX)       
	{
		pthread_mutex_unlock(&tasklock);		//和wait的功能差不多，没有资源就先释放锁
		usleep(10000);							//等待
		pthread_mutex_lock(&tasklock);			//在加锁

	}
	pthread_mutex_unlock(&tasklock);			//资源来了解锁


	//给任务队列添加一个节点 和初始化
	Task *newTask;
	newTask =(Task*) malloc(sizeof(Task));
	if(newTask == NULL)
	{
		preeor("malloc");
	}
	newTask->word = realword;			//函数指针赋值，直接把地址过去
	newTask->agr = agr;


	//添加任务到任务链表
	Task *member = pool->head;
	if( member == NULL)
	{
		member = newTask;	
	}else
	{
		while(member-> next != NULL)
		{
			member = member->next;
		}
		member->next = newTask;
	}
	pool->busywork++;


	//通知工作线程拿任务处理
	thread_cond_t_signal(&pool->newtask);
	pthread_mutex_unlock(&pool->testlock);

}


//4.实现工作线程
void *workthread(void* arg)
{
	while(1)
	{
		//没有任务，wait阻塞
		pthread_mutex_lock(&pool->tasklock);		 //访问工作队列加锁
		pthread_cond_wait(&pool->newTask);			////等待newtask到来

		task* phead = Pool->head;		//从头开始取
		pool->head = pool->head->next;	//头指针执行下一个

		//执行函数
		phead->fun(phead->arg);
		pool->busywork--;

	}


}


void pool_destory()
{
	//删除任务队列的所以节点，释放空间
	Task* head;
	while(pool->head->next != NULL)
	{
		head = pool->head;
		pool->head = pool->head->next;
		free(head);
	}

	//删除条件变量和互斥变量
	pthread_mutex_destorry(&pool->taskLock);
	pthread_cond_destroy(&pool->newTask);

	//释放整个线程池
	free(pool);
}

//============================================

int main()
{
	int i;
	pool_init();
	sleep(20);
	//创建工作任务
	for(i = 1; i <= 20, i++)
	{
		pool_add_task(i);
	
	}

	sleep(5);
	//释放空间和资源
	pool_destory();

	return 0;
}





















